package cn.iocoder.yudao.module.cms.benefit.service;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.cms.benefit.bo.BenefitCategoryBO;
import cn.iocoder.yudao.module.cms.benefit.dal.dataobject.BenefitDO;
import cn.iocoder.yudao.module.cms.benefit.dal.mysql.BenefitMapper;
import cn.iocoder.yudao.module.cms.benefit.vo.BenefitPageReqVO;
import cn.iocoder.yudao.module.cms.benefit.vo.BenefitSaveReqVO;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.api.cms.ErrorCodeConstants.BENEFIT_DUPLICATE;
import static cn.iocoder.yudao.module.api.cms.ErrorCodeConstants.BENEFIT_NOT_EXISTS;

/**
 * 权益保障 Service 实现类
 *
 * @author 山野羡民
 */
@Service
@Validated
public class BenefitServiceImpl implements BenefitService {

    @Resource
    private BenefitMapper benefitMapper;

    @Override
    public Long createBenefit(BenefitSaveReqVO reqVO) {
        validateBenefitDuplicate(reqVO.getName());
        // 插入
        BenefitDO benefitDO = BeanUtils.toBean(reqVO, BenefitDO.class);
        benefitMapper.insert(benefitDO);
        // 返回
        return benefitDO.getId();
    }

    @Override
    public void updateBenefit(BenefitSaveReqVO reqVO) {
        // 校验存在
        validateBenefitExists(reqVO.getId());
        // 更新
        BenefitDO benefitDO = BeanUtils.toBean(reqVO, BenefitDO.class);
        benefitMapper.updateById(benefitDO);
    }

    @Override
    public void deleteBenefit(Long id) {
        // 校验存在
        BenefitDO benefitDO = validateBenefitExists(id);
        // 删除
        benefitMapper.deleteById(benefitDO);
    }

    private BenefitDO validateBenefitExists(Long id) {
        BenefitDO benefitDO = benefitMapper.selectById(id);
        if (benefitDO == null) {
            throw exception(BENEFIT_NOT_EXISTS);
        }
        return benefitDO;
    }

    private void validateBenefitDuplicate(String name) {
        BenefitDO benefitDO = benefitMapper.selectOne(BenefitDO::getName, name);
        if (benefitDO != null) {
            throw exception(BENEFIT_DUPLICATE);
        }
    }

    @Override
    public BenefitDO getBenefit(Long id) {
        return benefitMapper.selectById(id);
    }

    @Override
    public PageResult<BenefitDO> getBenefitPage(BenefitPageReqVO pageReqVO) {
        return benefitMapper.selectPage(pageReqVO);
    }

    @Override
    public List<BenefitCategoryBO> getAllCategory() {
        return benefitMapper.selectAllCategory();
    }

    @Nonnull
    @Override
    public List<BenefitDO> getBenefitList(String category) {
        return benefitMapper.selectListByCategory(category);
    }

}
